package com.wanbatv.wangwangba;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.SeekBar;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wangwangba.util.BitmapCache;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;




/**
 *
 * @author zhangyus
 *
 */
public class AlbumFullScreenActivity extends FullScreenActivity implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener,SeekBar.OnSeekBarChangeListener, MediaPlayer.OnVideoSizeChangedListener {

	private ViewPager mViewPager;

	private ArrayList<ImageView> imageViews;
	ImageLoader mImageLoader = null;
	RequestQueue mRequestQueue = null;
	ImageView chengzhang_zanting;
	ImageView chengzhang_video_bg;
	SurfaceView[] surfaceView = null;
	MediaPlayer[] mediaPlay = null;
	SurfaceHolder[] surfaceholder = null;
	int num=0;
	private int mCurrentPosition = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_album_full_screen);

		ArrayList<String> urls = getIntent().getStringArrayListExtra("urls");
		final int length = urls != null ? urls.size() : 0;

		mediaPlay = new MediaPlayer[length];
		surfaceholder = new SurfaceHolder[length];
		surfaceView = new SurfaceView[length];

		final ArrayList<String> urls2 = getIntent().getStringArrayListExtra("urls2");
		final ArrayList<String> urls3 = getIntent().getStringArrayListExtra("urls3");
		int position = getIntent().getIntExtra("position", 0);
		imageViews = new ArrayList<ImageView>();
		mViewPager = (ViewPager) findViewById(R.id.albumVPager);
		mViewPager.setAdapter(new AlbumPagerAdapter(imageViews, urls, urls2,urls3));
		mViewPager.setCurrentItem(position);
		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				num=position;

				if (mCurrentPosition > -1 && mediaPlay[mCurrentPosition] != null) {
					try {
						if (mediaPlay[mCurrentPosition].isPlaying()) {
							mediaPlay[mCurrentPosition].reset();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				mCurrentPosition = position;

			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
	}

	@Override
	public void onCompletion(MediaPlayer mp) {

	}


	@Override
	public void onPrepared(MediaPlayer mp) {
		if (mp != null) {
			mp.start();
		}
	}


	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

	}


	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {

	}


	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {

	}

	@Override
	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		DisplayMetrics dm = new DisplayMetrics();
		Log.i("surfaceCallback", "@@@ onVideoSizeChanged w:" + width + ", h:" + height);
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		if (width > height) {
			float scale = (float) dm.widthPixels / width;
			width = dm.widthPixels;
			height = (int) (height * scale);
		} else {
			float scale = (float) dm.heightPixels / height;
			width = (int) (width * scale);
			height = dm.heightPixels;
		}
		Log.i("surfaceCallback", "@@@ onVideoSizeChanged after scale w:" + width + ", h:" + height);
		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) surfaceView[mViewPager.getCurrentItem()].getLayoutParams();
		if (lp.width != width || lp.height != height) {
			lp.width = width;
			lp.height = height;
			surfaceView[mViewPager.getCurrentItem()].setLayoutParams(lp);
		}
	}

	class AlbumPagerAdapter extends PagerAdapter {
		private ArrayList<ImageView> ivs;
		private ArrayList<String> urls;
		private ArrayList<String> urls2;
		private ArrayList<String> urls3;

		public AlbumPagerAdapter(ArrayList<ImageView> ivs,
				ArrayList<String> urls,ArrayList<String> urls2,ArrayList<String> urls3) {
			super();
			this.ivs = ivs;
			this.urls = urls;
			this.urls2 = urls2;
			this.urls3 = urls3;

		}

		public AlbumPagerAdapter() {
			super();
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return urls.size();
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (View) arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {

			container.removeView((View) object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			String panding=urls2.get(position);

//			container.addView(AppUtil.getInstance(AlbumFullScreenActivity.this)
//					.loadImageBitmap(imageView, url,false));

			if(panding.equals("img")) {
				ImageView imageView = new ImageView(AlbumFullScreenActivity.this);
				imageView.setLayoutParams(new LayoutParams(
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				imageView.setScaleType(ScaleType.FIT_CENTER);
				imageView.setVisibility(View.VISIBLE);
				imageView.setFocusable(true);
				String url = urls.get(position);
				mRequestQueue = Volley.newRequestQueue(AlbumFullScreenActivity.this.getApplicationContext());
				mImageLoader = new ImageLoader(mRequestQueue, new BitmapCache());
				mImageLoader.get(url, ImageLoader.getImageListener(
								imageView, 0, 0),
						imageView.getWidth(),
						imageView.getHeight(),
						ImageView.ScaleType.CENTER_CROP);
				container.addView(imageView);
				return imageView;
			}else{
				View layout = LayoutInflater.from(AlbumFullScreenActivity.this).inflate(R.layout.chengzhang_shipin_layout, null);
				container.addView(layout);
				surfaceView[position]=(SurfaceView)layout.findViewById(R.id.surfaceview_chengzhang);
				surfaceholder[position] = surfaceView[position].getHolder();
				surfaceholder[position].setFixedSize(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
				surfaceholder[position].addCallback(new SurfaceCallback(position));
				chengzhang_zanting=(ImageView)layout.findViewById(R.id.chengzhang_zanting);
				chengzhang_video_bg=(ImageView)layout.findViewById(R.id.chengzhang_video_bg);
				mImageLoader.get(urls3.get(position), ImageLoader.getImageListener(
								chengzhang_video_bg, 0, 0),
						chengzhang_video_bg.getWidth(),
						chengzhang_video_bg.getHeight(),
						ImageView.ScaleType.CENTER_CROP);
				chengzhang_zanting.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						v.setVisibility(View.GONE);
						chengzhang_video_bg.setVisibility(View.GONE);
						setbofang(position);
					}
				});
				return layout;
			}

		}
	}
	private void setbofang(int position){
		try {
			if (mediaPlay[position].isPlaying()) {
				mediaPlay[position].pause();
			} else {
				mediaPlay[position].start();
			}
		} catch (Exception e) {
			e.printStackTrace();
			mediaPlay[position].reset();
		}
		ArrayList<String> urls = getIntent().getStringArrayListExtra("urls");
		String url=urls.get(position);
		try {
			mediaPlay[position].setDataSource("http://cdn.wanbatv.com" + url + jiami(url));
			mediaPlay[position].prepareAsync();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private String jiami(String video_url){
		String url_team2=video_url;

		long time=System.currentTimeMillis();
		final String shijianchuo=Long.toHexString(time);
		final String key="w2nBa7VS1";

		String url_key=key+url_team2+shijianchuo;
		String key_1=string2MD5(url_key);
		String url_team="?auth_token="+key_1+"&auth_time="+shijianchuo;
		return url_team;
	}
	
	public static String string2MD5(String inStr){
		MessageDigest md5 = null;
		try{
			md5 = MessageDigest.getInstance("MD5");
		}catch (Exception e){
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++){
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString().toLowerCase();

	}

	private class SurfaceCallback implements SurfaceHolder.Callback {

		private int mPosition = -1;

		SurfaceCallback(int position) {
			mPosition = position;
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			mediaPlay[mPosition]=new MediaPlayer();
			mediaPlay[mPosition].setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlay[mPosition].setDisplay(holder);
			mediaPlay[mPosition].setOnPreparedListener(AlbumFullScreenActivity.this);
			mediaPlay[mPosition].setOnCompletionListener(AlbumFullScreenActivity.this);
			mediaPlay[mPosition].setOnVideoSizeChangedListener(AlbumFullScreenActivity.this);
		}


		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

		}


		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			mediaPlay[mPosition].release();
			mediaPlay[mPosition] = null;
		}
	}
}